package com.tfswue.cxy.service;

import com.tfswue.cxy.entity.Book;
import com.tfswue.cxy.mapper.BookMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    // 查询单本书
    public Book getBookById(Long id) throws Exception {
        String key = "book:" + id;
        String bookJson = redisTemplate.opsForValue().get(key);
        if (bookJson != null) {
            return objectMapper.readValue(bookJson, Book.class);
        }
        Book book = bookMapper.selectById(id);
        if (book != null) {
            redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(book), 1, TimeUnit.HOURS);
        }
        return book;
    }

    // 新增图书
    public void addBook(Book book) {
        bookMapper.insert(book);
        clearBookCache();
    }

    // 删除图书
    public void deleteBook(Long id) {
        bookMapper.deleteById(id);
        clearBookCache();
    }

    // 修改图书
    public void updateBook(Book book) {
        bookMapper.updateById(book);
        clearBookCache();
    }

    // 查询所有图书
    public List<Book> getAllBooks() {
        return bookMapper.selectList(null);
    }

    // 清除所有 book: 缓存
    private void clearBookCache() {
        Set<String> keys = redisTemplate.keys("book:*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}